package com.cluster.gulimall.product.app;

import com.cluster.gulimall.common.utils.R;
import com.cluster.gulimall.product.entity.PmsCategory;
import com.cluster.gulimall.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;



@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 查询出所有分类以及子分类，以树形结构组装起来列表
     */
    @GetMapping("/list/tree")
    //@RequiresPermissions("product:category:list")
    @ResponseBody
    public R list(){
        //三级分类目录树 最外面是一级,二级,三级
        List<PmsCategory> entities = categoryService.listWithTree();
        return R.ok().put("data", entities);
    }

    @GetMapping("/infos")
    //@RequiresPermissions("product:category:info")
    public R categoryInfo(@RequestParam("catId") Long catId){
        List<PmsCategory> categoryList = categoryService.getCategoryByName(catId);
        return R.ok().put("data", categoryList);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{catId}")
    //@RequiresPermissions("product:category:info")
    public R info(@PathVariable("catId") Long catId){
        PmsCategory category = categoryService.getById(catId);
        return R.ok().put("data", category);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    //@RequiresPermissions("product:category:save")
    public R save(@RequestBody PmsCategory category){
		categoryService.save(category);
        return R.ok();
    }

    @PutMapping("/update/sort")
    //@RequiresPermissions("product:category:update")
    public R updateSort(@RequestBody PmsCategory[] category){
        categoryService.updateBatchById(Arrays.asList(category));
        return R.ok();
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    //@RequiresPermissions("product:category:update")
    public R update(@RequestBody PmsCategory category){
		categoryService.updateCascade(category);
        return R.ok();
    }

    /**
     * 删除
     * @RequestBody:获取请求体，必须发送POST请求
     * SpringMVC自动将请求体的数据(json)转换为对象
     */
    @DeleteMapping("/delete")
    //@RequiresPermissions("product:category:delete")
    public R delete(@RequestBody Long[] catIds){

        //1、检查当前删除的菜单，是否被别的地方引用
		//categoryService.removeByIds(Arrays.asList(catIds));
		categoryService.removeMenuByIds(Arrays.asList(catIds));
        return R.ok();
    }

}
